﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using DG.Tweening;

public partial class BattleCtr: XObjBase
{
  
    private Dictionary<string, UIBattlePlayer> _userId2UIBattlePlayer;
    private void OnInitRender()
    {
        _userId2UIBattlePlayer = new Dictionary<string, UIBattlePlayer>();
    }


    private IEnumerator CoWaitUIBattle()
    {
        yield return new WaitUntil(() => { return UIBattle.Instance != null; });
        //绑定数据
        if(UIBattle.Instance.dataBattleMgr == null)
            UIBattle.Instance.Bind(_dataBattleMgr);
        int playerCount = _dataBattleMgr.GetDataPlayerCount();
        for (int i = 0; i < playerCount; i++)
        {
            var dataPlayer = _dataBattleMgr.GetDataPlayer(i);
            int index = i;

            //已经生成了，只修改挂点
            var player = GetUIBattlePlayer(dataPlayer.GetUserId());
            if (player != null)
            {
                int showIndex = _dataBattleMgr.GetShowIndex(index);
                player.SetShowIndex(showIndex);
                Debug.Log(dataPlayer.GetUserName() + "已存在");
                continue;
            }

            XFactory.Instance.CreateInstanceAsync("UIBattlePlayer", null, (vGameObject) =>
            {
                int showIndex = _dataBattleMgr.GetShowIndex(index);

                //已经生成了，只修改挂点
                var player = GetUIBattlePlayer(dataPlayer.GetUserId());
                if (player != null)
                {
                    player.SetShowIndex(showIndex);
                    Debug.Log(dataPlayer.GetUserName() + "已生成存在");
                    return;
                }

                //vGameObject.transform.SetParent(UIBattle.Instance.playerRoots[showIndex].transform, false);
                var cmp = vGameObject.GetComponent<UIBattlePlayer>();
                cmp.Bind(dataPlayer);

                //决定挂在哪个点上
                cmp.SetShowIndex(showIndex);

                //缓存
                SetUIBattlePlayer(dataPlayer.GetUserId(), cmp);
            });
        }
    }

    public void SetUIBattlePlayer(string userId, UIBattlePlayer vUIBattlePlayer)
    {
        _userId2UIBattlePlayer[userId] = vUIBattlePlayer;
    }

    public UIBattlePlayer GetUIBattlePlayer(string userId)
    {
        UIBattlePlayer uiBattlePlayer;
        _userId2UIBattlePlayer.TryGetValue(userId, out uiBattlePlayer);
        return uiBattlePlayer;
    }

}